package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.zhxu.bs.operator.Empty;
import com.jwm.power.mapper.TasklstMapper;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.Logs;
import com.jwm.power.model.entity.TaskLst;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.entity.Workordertypes;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.LogsRepository;
import com.jwm.power.repository.TaskRepository;
import com.jwm.power.repository.UsersRepository;
import com.jwm.power.service.TaskService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private LogsRepository logsRepository;
    @Autowired
    private TasklstMapper tasklstMapper;
    // 设置任务列表
    @Override
    public ResponseData SaveTasklst(HttpServletRequest request) {
        try {
            Users users = (Users) StpUtil.getSession().get("users");
            TaskLst model_New = new TaskLst();
            ServletRequestDataBinder binder =
                    new ServletRequestDataBinder(model_New);
            binder.bind(request);
            Integer operationType = 0;
            if (Optional.ofNullable(model_New.getId()).isPresent()) {
                operationType = 1;
                TaskLst taskLst = taskRepository.findByid(model_New.getId());
                if (!taskLst.getTaskcontent().equals(model_New.getTaskcontent())) {
                    return new ResponseData(EnumResult.WORK_FAIL_TNAME, model_New);
                }
            } else {
                String taskcode = Optional.ofNullable(users.getCustomerCode()).isPresent() ? users.getCustomerCode() : "0";
                model_New.setTaskcode(String.format("%08d", Integer.parseInt(taskcode) + 1));
            }
            model_New.setTaskstatus("-2");

            String taskfirstdate = request.getParameter("taskfirstdate");
            String taskplanenddate = request.getParameter("taskplanenddate");
            String taskenddate = request.getParameter("taskenddate");
            String taskfeedbackdate = request.getParameter("taskfeedbackdate");
            String latefeedbackdate = request.getParameter("latefeedbackdate");

            // 计划开始时间
            model_New.setTaskfirstdate(Ut.formatStrToDate(taskfirstdate, "yyyy-MM-dd"));

            // 计划完成时间
            System.out.println("转换后的值："+Ut.formatStrToDate(taskplanenddate, "yyyy-MM-dd"));
            model_New.setTaskplanenddate(Ut.formatStrToDate(taskplanenddate, "yyyy-MM-dd"));

            //** ----------------这里检测是否为空会将空值自动带入到Ut.formatStrToDate()方法中，不影响插入，但是会报错。----------------- */
            // 实际完成时间
            if(Objects.equals(taskenddate, "--") || taskenddate.isEmpty()){}else{
            model_New.setTaskenddate(Ut.formatStrToDate(taskenddate, "yyyy-MM-dd"));
            };

            // 反馈时间
            if(Objects.equals(taskfeedbackdate, "--") || taskfeedbackdate.isEmpty()){}else {
                model_New.setTaskfeedbackdate(Ut.formatStrToDate(taskfeedbackdate, "yyyy-MM-dd"));
            };

            // 逾期时间
            if(Objects.equals(latefeedbackdate, "--") || latefeedbackdate.isEmpty()){}else {
                model_New.setLatefeedbackdate(Ut.formatStrToDate(latefeedbackdate, "yyyy-MM-dd"));
            };

            // 插入数据到数据库
            taskRepository.save(model_New);

            // 日志
            Logs log = Ut.SaveLog("tasklst", model_New.getTaskcode(), operationType == 1 ? EnumOperate.EDIT : EnumOperate.ADD, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, model_New);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
    //更新当前表单的已读状态
    @Override
    public ResponseData TaskIsRead(HttpServletRequest request){
        try {
            String dataId = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            HashMap<String, Object> map = new HashMap<>();
            map.put("tName", "TaskLst");
            String values = " taskisread=1";
            map.put("values",values);
            map.put("strWhere", " where id ='" + dataId + "'");
            tasklstMapper.updateDefined(map);
            // 添加日志
            Logs log = Ut.SaveLog(dataType, dataId, EnumOperate.DELETE, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    @Override
    public ResponseData UpdateOverfeedback(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String overduefeedback = request.getParameter("overduefeedback");
            String latefeedbackdate =request.getParameter("latefeedbackdate");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            HashMap<String, Object> map = new HashMap<>();
            map.put("tName", "TaskLst");
            String values = "overduefeedback='"+ overduefeedback + "', latefeedbackdate= '" + latefeedbackdate + "', taskstatus=0";
            map.put("values", values);
            map.put("strWhere", "where id = " + dataId);
            tasklstMapper.updateDefined(map);
            Logs logs = Ut.SaveLog(dataType, dataId, EnumOperate.DELETE, users);
            logsRepository.save(logs);
            return new ResponseData(EnumResult.SUCCESS, null);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    @Override
    public ResponseData UpdateComplate(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String taskendfeedback = request.getParameter("taskendfeedback");
            String taskendfeedbackdate =request.getParameter("taskendfeedbackdate");
            System.out.println(taskendfeedback);
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            HashMap<String, Object> map = new HashMap<>();
            map.put("tName", "TaskLst");
            String values = "taskendfeedback='"+ taskendfeedback + "', taskenddate='" + taskendfeedbackdate + "', taskstatus=3";
            map.put("values", values);
            map.put("strWhere", "where id = " + dataId);
            tasklstMapper.updateDefined(map);
            Logs logs = Ut.SaveLog(dataType, dataId, EnumOperate.DELETE, users);
            logsRepository.save(logs);
            return new ResponseData(EnumResult.SUCCESS, null);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
}
